package com.lb.imgzip;

import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;

/**
 * @version 1.0
 * @Author: Edward
 * @Date: 2022/1/12 10:05
 * @Description:
 */
public class ImageTest {

    public static void main(String[] args) throws Exception {
//        Thumbnails.of(new File("D:/11/123.jpg"))
//                .scale(1f) //图片大小（长宽）压缩比例 从0-1，1表示原图
////                .outputQuality(0.5f) //图片质量压缩比例 从0-1，越接近1质量越好
//                .toOutputStream(new FileOutputStream("D:/11/456.jpg"));

        File file=new File("D:/11/123.jpg");
        byte[] b = File2byte(file);
        commpressPicCycle(b,10 * 1024,0.9);
    }

    public static byte[] File2byte(File tradeFile){
        byte[] buffer = null;
        try
        {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return buffer;
    }

    public static FileOutputStream commpressPicCycle(byte[] bytes, long desFileSize, double accuracy) throws IOException {
        long srcFileSizeJPG = bytes.length;
        System.out.println(srcFileSizeJPG);
        // 2、判断大小，如果小于，不压缩；如果大于等于，压缩
        if (srcFileSizeJPG <= desFileSize * 1024) {
            File file = new File("D://11/888.png");
            FileOutputStream fileOutputStream=new FileOutputStream(file);
            fileOutputStream.write(bytes);
            fileOutputStream.close();;
            return fileOutputStream;
        }
        // 计算宽高
        BufferedImage bim = ImageIO.read(new ByteArrayInputStream(bytes));
        int srcWdith = bim.getWidth();
        int srcHeigth = bim.getHeight();
        int desWidth = new BigDecimal(srcWdith).multiply(
                new BigDecimal(accuracy)).intValue();
        int desHeight = new BigDecimal(srcHeigth).multiply(
                new BigDecimal(accuracy)).intValue();

        //字节输出流（写入到内存）
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Thumbnails.of(new ByteArrayInputStream(bytes)).size(desWidth, desHeight).outputQuality(accuracy).toOutputStream(baos);
        byte[] bytes1 = baos.toByteArray();
        baos.close();
        return commpressPicCycle(bytes1, desFileSize, accuracy);
    }
}
